package com.kennedy.springbootjpa.web.controller;

import com.kennedy.springbootjpa.beans.Shop;
import com.kennedy.springbootjpa.beans.common.ResultMsg;
import com.kennedy.springbootjpa.service.ShopService;
import com.kennedy.springbootjpa.utils.FileUploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * Created by 51102 on 2017/6/18.
 */
@Controller
@RequestMapping("/shop")
public class ShopController {
    @Autowired
    private ShopService shopService;

    @Value("${staticPath}")
    private String staticPath;

    @GetMapping("/toList")
    public String toList() {
        return "/shop/list";
    }

    @GetMapping("/toAdd")
    public String toAdd() {
        return "/shop/add";
    }

    @RequestMapping(value = "/upload", method = RequestMethod.GET)
    public String toUpload() {
        return "/product/upload";
    }

    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam(value = "product", required = true) MultipartFile file) {
        String fileName = System.currentTimeMillis() + ".png";
        // 判断文件是否为空
        if (!file.isEmpty()) {
            try {
                // 转存文件
                file.transferTo(new File("E:/pic/" + fileName));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return fileName;
    }

    @GetMapping("/getListByPage")
    @ResponseBody
    public Page<Shop> getListByPage(Shop shop) {
        Page<Shop> shops = shopService.getListByPage(shop);
        return shops;
    }

    @GetMapping("/get/{id}")
    @ResponseBody
    public Shop get(@PathVariable("id") long id) {
        return shopService.selectOne(id);
    }

    @PostMapping("/add")
    @ResponseBody
    public ResultMsg add(Shop shop, @RequestParam(value = "logo", required = true) MultipartFile file) {
        FileUploadUtil.FileResponse fileResponse = FileUploadUtil.uploadFile(file, staticPath + "/shops/" + shop.getId());
        shop.setLogoUrl("/shops/" + shop.getId() + "/" + fileResponse.getNewFileName());
        shopService.insert(shop);
        return ResultMsg.success();
    }
}
